<template>
  <div class="appointmentHistory-page">
    <GhNavBar title="用户预约记录"  />
    <div class="date-search">
        <div class="start-content"><span>起始日期:</span>
            <div class="startTime"  @click="setCurrentTime('start')">{{startTime}}</div>
        </div>
          <!-- 展示日期选择器   -->
          <van-popup v-model:show="showPicker" round position="bottom">
            <van-datetime-picker
                v-model="selectedDay"
                type="date"
                title="请选择日期"
                :min-date="minDate"
                :max-date="maxDate"
                @cancel="showPicker=false"
                @confirm="onConfirm"
                :format="dateFormat"
          />
        </van-popup> 
        <div class="end-content"><span>结束日期:</span>
            <div class="endTime" @click="setCurrentTime('end')">{{endTime}}</div>
        </div>
    </div>
    <div class="tabs-search">
         <div class="tabs">
              <button class="tod-btn" @click="selectTod_btn">今日</button>
              <button class="tow-btn"  @click="selectTow_btn">明日</button>
              <button class="btn-search" @click="selectBtn">搜索</button>
         </div>
    </div>
    <div class="table">
           <van-list
    v-model:loading="loading"
    :finished="finished"
    finished-text="没有更多了"
    v-if="items.length>0"
  >
    <van-cell v-for="item in items" :key="item.id"  >
        <div class="content_box" >
            <div class="header">
                <div class="left-head" >
                    <gh-icon class="icon" name="consult-zixunshi" />
                    <span>{{item.username}}</span>
                    <span class="arrow">></span>
                </div>
                <div class="right-head">{{getStatusInChinese(item.status)}}</div>
             </div>
             <div class="middle" >
                <div class="pic_box">
                    <img :src="item.avatar">
                </div>
                <div class="timeInfo">
                    <p class="date">  预约时间：{{item.date}}  </p>
                    <p class="timeSlot"> {{item.start_time}}-{{item.end_time}}</p>
                </div>
                <div class="price">￥120</div>
             </div>
             <div class="bottom">
                <div class="more">更多</div>
                <div class="again"  v-if="item.status=='Scheduled'" @click="handleAction(item)">
                   取消预约
                </div>
             </div>
        </div>
    </van-cell>
    
  </van-list>
  <div class="nothing-info" v-else>
    <van-empty  image-size="100"  image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" description="暂预约信息" />
  </div>
    </div>
  </div>
</template>

<script setup>
import {ref,reactive,onBeforeMount,computed,onMounted,watch} from "vue"
import { Toast, Dialog } from 'vant';
import 'vant/es/toast/style'
import{useRouter,useRoute}from 'vue-router'
import { cancelBooking}from '@/services/booking'
import{ getconsultantInfoByaccount,getAppointmentInfoBycoun_id,getappo_infoBystart_endTime}from '@/services/consultant'
const router =useRouter();  
const route =useRoute()
const showPicker=ref(false)
const currentDiv=ref('')
const setCurrentTime = (type) => {
      currentDiv.value = type;
      showPicker.value = true;
    };
//搜索今日的数据函数
const selectTod_btn=async()=>{
    const id =personalInfo.value.id
    const start=formattedDay(new Date())
    const end=formattedDay(new Date())
  const res=await  getappo_infoBystart_endTime(id,start,end)
   const rows=res.data
     rows.forEach(row => {
    const { totalChunks, base64Chunks } = row.avatar;
    let imageData;
    for (let i = 0; i < base64Chunks.length; i++) {
      const base64Data = base64Chunks.join('');
      imageData = `data:image/jpeg;base64,${base64Data}`;
      row.avatar = imageData;
    }
  });
     items.value=rows
}
//搜索明日的数据函数
const selectTow_btn=async()=>{
    const id =personalInfo.value.id
    const start=formattedDay(new Date().setDate(new Date().getDate()+1))
    const end=formattedDay(new Date().setDate(new Date().getDate()+1))
  const res=await  getappo_infoBystart_endTime(id,start,end)
   const rows=res.data
     rows.forEach(row => {
    const { totalChunks, base64Chunks } = row.avatar;
    let imageData;
    for (let i = 0; i < base64Chunks.length; i++) {
      const base64Data = base64Chunks.join('');
      imageData = `data:image/jpeg;base64,${base64Data}`;
      row.avatar = imageData;
    }
  });
     items.value=rows
}
//搜索按钮的函数
const selectBtn=async()=>{
    const id =personalInfo.value.id
  const res=await  getappo_infoBystart_endTime(id,startTime.value,endTime.value)
   const rows=res.data
     rows.forEach(row => {
    const { totalChunks, base64Chunks } = row.avatar;
    let imageData;
    for (let i = 0; i < base64Chunks.length; i++) {
      const base64Data = base64Chunks.join('');
      imageData = `data:image/jpeg;base64,${base64Data}`;
      row.avatar = imageData;
    }
  });
     items.value=rows
}
//定义时间选择器信息
    const minDate = new Date(new Date().getFullYear()-1);
    const maxDate = new Date(); 
    const dateFormat = 'yyyy-MM-dd';
    const selectedDay=ref(new Date())
    //起始日期·结束日期
    const formattedDay=(value)=>{
        const date = new Date(value);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');  
        const formattedDate = `${year}-${month}-${day}`;
        return formattedDate
    }
       
 const startTime=ref(formattedDay(new Date()))
 const endTime=ref(formattedDay(new Date()))

const loading = ref(false);
const finished = ref(false);
//用户预约记录响应式变量
const items=ref({})
//咨询师个人信息
const personalInfo=ref('')
onBeforeMount(() => {
  init();
});

const init=async()=>{
    // 在这里处理数据，这里只是一个简单示例
  if (items && items.length > 0) {
    // 处理数据逻辑，可以根据实际数据结构进行遍历和处理
     console.log('1')
  } else {
    // Toast('没有数据');
    finished.value = true;
  }
}
//组件挂载时加载数据
onMounted(async()=>{
    const account=JSON.parse(localStorage.getItem('gh-user')).user.userData.account
    const res=await getconsultantInfoByaccount(account)
    personalInfo.value=res.data
    const id =personalInfo.value.id
     const infoData=await getAppointmentInfoBycoun_id(id)
     const rows=infoData.data
     rows.forEach(row => {
    const { totalChunks, base64Chunks } = row.avatar;
    let imageData;
    for (let i = 0; i < base64Chunks.length; i++) {
      const base64Data = base64Chunks.join('');
      imageData = `data:image/jpeg;base64,${base64Data}`;
      row.avatar = imageData;
    }
  });
     items.value=rows
})
//定义方法接收status并返回对应的中文值
const getStatusInChinese=(status)=>{
    return status === 'Scheduled' ? '待使用' :
             status === 'Completed' ? '已完成' :
             status === 'Cancelled' ? '已取消' :
             status;
}
const handleAction=async(item)=>{
    await Dialog.confirm({
    title: '温馨提示',
    message: '您确认要取消预约码？'
  })
   .then(async() => {
     const formData=new FormData()
     formData.append('coun_id',item.id)
     formData.append('appointment_id',item.appointment_id)
     formData.append('start_time',item.start_time)
     formData.append('date',item.date)
     formData.append('end_time',item.end_time)
     const res=await cancelBooking(formData).then((response)=>{
      return response
    }).catch((error)=>{
     return error
    });
    console.log(res)
    if(res.status!==201){
   if(res.response.status==402){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
    }
    if(res.response.status==404){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
    }
    }
    Toast.success('已取消预约')
    // 强制刷新当前页面
    location.reload(true);
  })
  .catch(() => {
    Toast('取消操作')
  });
}
//选择日期
const onConfirm = (value) => {
        const date = new Date(value);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');  
        const formattedDate = `${year}-${month}-${day}`;
        if(currentDiv.value==='start'){
           startTime.value=formattedDate
        }
        if(currentDiv.value==='end'){
           endTime.value=formattedDate
        }
        showPicker.value=false
    };

</script>

<style lang="scss" scoped>
.appointmentHistory-page{
    width: 100%;
    display: flex;
   .date-search{
       width: 100%;
       margin-top: 38px;
       position: fixed;
       display: flex;
       background-color: #fff;
       height: 40px;
       align-items: center;
       z-index: 99;
       justify-content: space-around;
       padding: 0 10px;
       font-size: 16px;
       .start-content,.end-content{
        display: flex;
        .startTime,.endTime{
            margin-left: 10px;
            border-bottom: 1px solid var(--gh-text3);
            font-size: 14px;
            text-align: center;
        }
        span{
            font-weight: bold;
        }
           
       }
   }
   .tabs-search{
      position: fixed;
      padding: 15px 10px;
      background-color: #fff;
      width: 100%;
      top: 80px;
      z-index: 1;
      left: 0;
      .tabs{
         position: relative;
         left: 30%;
         button{
            width: 70px;
            border: none;
            margin: 0 4px;
            border-radius: 8px;
         }
         .tod-btn{
            &:active{
                background-color: #f5f5f5;
            }
         }
         .tow-btn{
            &:active{
                background-color: #f5f5f5;
            }
         }
         .btn-search{
                background-color:var(--gh-primary);
                color: #fff;
                &:active{
                    background-color: #f5f5f5;
                }
            }

      }
   }
   .table{
       margin-top: 105px;
       width: 100%;
       .van-cell{
        width: 100%;
        padding: 10px;
        margin-top:10px;
        /* border-bottom: 10px solid #f5f5f5; */
        background-color:#fff;
        .content_box{
            width: 100%;
            height: 100%;
            .header{
                display: flex;
                align-items: center;
                width: 100%;
                height: 30px;
                padding: 0 20px;
                justify-content: space-between;
                .left-head{
                    .icon{
                    margin-top: 4px;
                    font-size: 16px;
                    top: 10px;
                    margin-right: 10px;
                }
                span{
                    font-size: 14px;
                    font-weight: bold;
                 }
                 .arrow{
                    font-size: 12px;
                    color: var(--gh-dark);
                    margin-left: 10px;
                 }
               }
               .right-head{
                   color: var(--gh-text3);
               }
            }
            .middle{
                 width: 100%;
                 padding: 10px 20px;
                 display: flex;
                 justify-content: space-around;
                 align-items: center;
                 .pic_box{
                    width: 50px;
                    height: 50px;
                    img{
                        display: block;
                        width: 100%;
                        height: 100%;
                        border-radius: 10px;
                    }
                 }
                 .timeInfo{
                    font-size: 12px;
                    .date{
                        font-weight: bold;
                    }
                    .timeSlot{
                        font-size: 14px;
                    }
                 }
                 .price{
                    color: var(--gh-price);
                    font-size: 16px;
                    font-weight: bold;
                 }
            }
            .bottom{
                display: flex;
                justify-content: space-between;
                margin-top: 8px;
                padding: 0 25px;
                .more{
                    color: var(--gh-text3);
                    font-size: 12px;
                    font-family: '黑体';
                }
                .again{
                    width: 80px;
                    text-align: center;
                    border: 1px solid var(--gh-primary);
                    border-radius: 8px;
                    font-size: 12px;
                    font-family: '黑体';
                }
            }
        }
     }
   }

}

</style>
